package com.agenda;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.database.Cursor;

public class AgregarUsuario extends Activity {
	
	private DBAdapter DB;
	private Cursor cursor;
	
	//private String login, pass, valido;
	private EditText user, pass1, pass1r, cad;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ah_agregar_usuario);
        
        DB = new DBAdapter(this);
        DB.open(); 
        
        cursor = DB.fetchAllUsuarios();
        cursor.moveToLast();
        
        user = (EditText)findViewById(R.id.ah_edit1);
        pass1 = (EditText)findViewById(R.id.ah_edit2);
        pass1r = (EditText)findViewById(R.id.ah_edit3);
        cad = (EditText)findViewById(R.id.ah_edit4);
        
        
        
}
    
    public void salir(View view){
    	finish();
    }
    
    public void agregarUsuario(View view) {
    	
    	if( isEmpty(user) || isEmpty(pass1) || isEmpty(pass1r) || isEmpty(cad) ) {
    		Toast.makeText(this, "* Campos Obligatorios", Toast.LENGTH_LONG).show();
    	} else {
    		
    		if( pass1.getText().toString().matches( pass1r.getText().toString() ) ) {
        		if( DB.createUsuario(user.getText().toString(), pass1.getText().toString(), 
        				cad.getText().toString(), getDatePhone() ) != -1 ) {
        			Toast.makeText(this, "Usuario Creado", Toast.LENGTH_LONG).show();
        		}
        		else {
        			Toast.makeText(this, "Error! al Crear Usuario", Toast.LENGTH_LONG).show();
        		}
        	}
        	else {
        		Toast.makeText(this, "Passwords NO Coinciden", Toast.LENGTH_LONG).show();
        		pass1.setText("");
        		pass1r.setText("");
        	}
        	
        	salir( view );
    		
    	}
    	
    	
    }
    
    
    private String getDatePhone()
    {
    	Calendar cal = new GregorianCalendar();
    	Date date = cal.getTime();
    	SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    	String formatteDate = df.format(date);
    	
    	return formatteDate;
    }
    
    private boolean isEmpty(EditText etText) {
    	if(etText.getText().toString().trim().length() > 0)
    		return false;
    	else
    		return true; 
    }
    
}
